﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/


using System;
using System.IO;
using Tesla.Core;
using Tesla.Graphics;
using Tesla.Math;
using SD = System.Drawing;

namespace Tesla.Content.Loaders.Image {
    public class JPGLoader : ResourceLoader<Texture> {

        public JPGLoader() 
            : base(".jpg") {

        }

        public override Texture Load(IResource resource, LoaderParameters parameters) {
            Stream str = resource.OpenStream();
            SD.Bitmap bitmap = new SD.Bitmap(str);

            ImageLoaderParameters imageParams = parameters as ImageLoaderParameters;
            if(imageParams != null) {
                if(imageParams.FlipImage) {
                    bitmap.RotateFlip(SD.RotateFlipType.RotateNoneFlipY);
                }
            }

            byte[] data = GetData(bitmap);
            SD.Imaging.PixelFormat pixelFormat = bitmap.PixelFormat;
            Color[] colors = null;
            switch(pixelFormat) {
                case SD.Imaging.PixelFormat.Format32bppArgb:
                    colors = GetRGBA(bitmap, data);
                    break;
                case SD.Imaging.PixelFormat.Format24bppRgb:
                    colors = GetRGB(bitmap, data);
                    break;
                case SD.Imaging.PixelFormat.Format8bppIndexed:
                    colors = GetIndexed(bitmap, data);
                    break;
                default:
                    throw new InvalidOperationException("Cannot read from that format encoding");
            }

            Texture2D tex = new Texture2D(bitmap.Width, bitmap.Height, true, SurfaceFormat.Color, new DataBuffer<Color>(colors));
            tex.Name = resource.Name;

            bitmap.Dispose();
            str.Close();

            return tex;
        }

        private static byte[] GetData(SD.Bitmap bitmap) {
            int formatSize = SD.Image.GetPixelFormatSize(bitmap.PixelFormat) / 8;
            int stride = bitmap.Width * formatSize;
            int width = bitmap.Width;
            int height = bitmap.Height;
            byte[] bytes = new byte[stride * height];

            IntPtr ptr = Tesla.Util.MemoryHelper.PinObject(bytes);
            SD.Imaging.BitmapData data = new SD.Imaging.BitmapData {
                Width = width,
                Height = height,
                Stride = stride,
                Scan0 = ptr
            };

            bitmap.LockBits(new SD.Rectangle(0, 0, width, height), SD.Imaging.ImageLockMode.ReadOnly | SD.Imaging.ImageLockMode.UserInputBuffer, bitmap.PixelFormat, data);
            bitmap.UnlockBits(data);
            Tesla.Util.MemoryHelper.UnpinObject(bytes);

            return bytes;
        }

        private static Color[] GetRGB(SD.Bitmap bitmap, byte[] data) {
            int width = bitmap.Width;
            int height = bitmap.Height;
            int totalSize = width * height;
            Color[] colors = new Color[totalSize];

            for(int i = 0, index = 0; i < totalSize; i++, index += 3) {
                byte b = data[index];
                byte g = data[index+1];
                byte r = data[index+2];
                colors[i] = new Color(r, g, b);
            }

            return colors;
        }

        private static Color[] GetRGBA(SD.Bitmap bitmap, byte[] data) {
            int width = bitmap.Width;
            int height = bitmap.Height;
            int totalSize = width * height;
            Color[] colors = new Color[totalSize];
            for(int i = 0, index = 0; i < totalSize; i++, index += 4) {
                byte b = data[index];
                byte g = data[index+1];
                byte r = data[index+2];
                byte a = data[index+3];
                colors[i] = new Color(r, g, b, a);
            }

            return colors;
        }

        private static Color[] GetIndexed(SD.Bitmap bitmap, byte[] data) {
            int width = bitmap.Width;
            int height = bitmap.Height;
            int totalSize = width * height;
            SD.Imaging.ColorPalette palette = bitmap.Palette;
            Color[] colors = new Color[totalSize];

            for(int i = 0; i < totalSize; i++) {
                int index = data[i];
                SD.Color c = palette.Entries[index];
                colors[i] = new Color(c.R, c.G, c.B, c.A);
            }
            return colors;
        }
    }
}
